<!DOCTYPE html>
<html>
<head>
  <title>学生信息查询</title>
  <meta charset="UTF-8">
  <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<h2>学生信息查询</h2>
<form id="addStudentForm">
  <label for="name">姓名：</label>
  <input type="text" name="name" id="name"><br><br>
  <label for="number">学号：</label>
  <input type="text" name="number" id="number"><br><br>
  <input type="submit" value="添加学生">
</form>
<br>
<table border="1">
  <thead>
  <tr>
    <th>ID</th>
    <th>姓名</th>
    <th>学号</th>
  </tr>
  </thead>
  <tbody id="studentTable">
  </tbody>
</table>
<script>
  // 查询学生信息并展示
  function showStudentTable() {
    $.ajax({
      url: "/api/students",
      type: "GET",
      dataType: "json",
      success: function(data) {
        if (data) {
          var studentTable = $("#studentTable");
          studentTable.empty();
          $.each(data, function(index, student) {
            studentTable.append("<tr><td>" + student.id + "</td><td>" + student.name + "</td><td>" + student.number + "</td></tr>");
          });
        }
      },
      error: function(xhr, status, error) {
        alert("查询学生信息失败：" + error);
      }
    });
  }
  // 添加学生
  $("#addStudentForm").submit(function(event) {
    event.preventDefault(); // 阻止表单提交
    var name = $("#name").val();
    var number = $("#number").val();
    if (!name || !number) {
      alert("姓名和学号不能为空！");
      return;
    }
    $.ajax({
      url: "/api/students",
      type: "POST",
      data: JSON.stringify({"name": name, "number": number}),
      contentType: "application/json",
      success: function(data) {
        alert("添加学生成功！");
        showStudentTable(); // 添加成功后刷新表格
      },
      error: function(xhr, status, error) {
        alert("添加学生失败：" + error);
      }
    });
  });

  // 页面加载时展示学生信息
  showStudentTable();
</script>

</body>
</html>

